<template>
  <div class="home-container">
    <el-card class="welcome-card">
      <template #header>
        <div class="card-header">
          <h2>欢迎使用微信消息转发助手</h2>
        </div>
      </template>
      <div class="welcome-content">
        <p>这是一个专注于将微信群内特定用户的消息转发给他人的桌面应用。</p>
        <p>当前状态：<span :class="{ 'status-running': wechatStore.isRunning, 'status-stopped': !wechatStore.isRunning }">{{ wechatStore.isRunning ? '服务运行中' : '服务已停止' }}</span></p>
        <p>登录状态：{{ isLoggedIn ? '已登录' : '未登录' }}</p>
        <div class="action-buttons">
          <el-button type="primary" @click="startService" :disabled="wechatStore.isRunning" :loading="isStarting">启动服务</el-button>
          <el-button type="success" @click="restartService" :loading="isLoggedInLoading" :disabled="isLoggedIn">确认登录完成</el-button>
          <el-button type="danger" @click="stopService" :disabled="!wechatStore.isRunning" :loading="isStopping">停止服务</el-button>
        </div>
      </div>
    </el-card>
    
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="8">
        <el-card class="stat-card">
          <h3>转发规则</h3>
          <div class="stat-value">{{ wechatStore.forwardingRules.length }}</div>
          <el-button type="text" @click="$router.push('/forwarding')">管理规则</el-button>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="stat-card">
          <h3>监控群组</h3>
          <div class="stat-value">{{ wechatStore.selectedGroups.length }}</div>
          <el-button type="text" @click="$router.push('/forwarding')">管理群组</el-button>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="stat-card">
          <h3>最近日志</h3>
          <div class="stat-value">{{ wechatStore.logs.length }}</div>
          <el-button type="text" @click="$router.push('/logs')">查看日志</el-button>
        </el-card>
      </el-col>
    </el-row>
    
    <el-card class="quick-start-card">
      <template #header>
        <div class="card-header">
          <h2>快速开始</h2>
        </div>
      </template>
      <ol class="quick-start-steps">
        <li>
          <h4>第一步：启动微信服务</h4>
          <p>点击上方的"启动服务"按钮，系统将自动启动微信和接口服务。</p>
        </li>
        <li>
          <h4>第二步：配置转发规则</h4>
          <p>前往"消息转发"页面，选择需要监控的群组和用户，设置转发规则。</p>
        </li>
        <li>
          <h4>第三步：开始转发</h4>
          <p>配置完成后，系统将自动监控指定群组中的消息，并按照规则进行转发。</p>
        </li>
      </ol>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useWechatStore } from '../store';
import { ElMessage } from 'element-plus';

const wechatStore = useWechatStore();
const isStarting = ref(false);
const isStopping = ref(false);

// 使用计算属性，与 Pinia store 保持同步
const isLoggedIn = computed(() => wechatStore.isLoggedIn);
const isLoggedInLoading = ref(false);

async function restartService() {
  isLoggedInLoading.value = true
  try {
    wechatStore.log('正在检查微信登录状态...');
    
    // 先检查服务是否运行
    try {
      const serviceStatus = await window.electronAPI.checkWechatService();
      wechatStore.log(`检查服务状态结果: ${JSON.stringify(serviceStatus)}`);
      
      if (!serviceStatus.running) {
        wechatStore.error('微信服务未运行，请先启动服务');
        ElMessage.error('微信服务未运行，请先点击"启动服务"按钮');
        return;
      }
    } catch (statusError) {
      wechatStore.error(`检查服务状态失败: ${statusError.message}`);
    }
    
    // 尝试调用登录检查API
    try {
      wechatStore.log('调用 /wcf/is_login 接口...');
      const loginResult = await window.electronAPI.getWechatApi('/wcf/is_login');
      wechatStore.log(`登录状态检查结果: ${JSON.stringify(loginResult)}`);
      
      // 检查返回的数据格式
      if (loginResult && loginResult.Payload === true) {
        // 更新 Pinia store
        wechatStore.updateStatus({ running: true, loggedIn: true });
        ElMessage.success('微信已成功登录');
        
        // 额外获取用户信息
        try {
          wechatStore.log('正在获取用户信息...');
          const userInfo = await window.electronAPI.postWechatApi('/wcf/self_info', {
            is_chatroom: false
          });
          wechatStore.log(`获取用户信息成功: ${JSON.stringify(userInfo)}`);
          
          if (userInfo && userInfo.Payload) {
            wechatStore.setUserInfo(userInfo.Payload);
            ElMessage.success('用户信息获取成功');
            ElMessage.success('现在您可以在"消息转发"页面配置转发规则');
          } else {
            wechatStore.log('用户信息数据格式不正确');
            ElMessage.warning('用户信息获取失败，但登录状态已确认');
          }
        } catch (infoError) {
          wechatStore.error(`获取用户信息失败: ${infoError.message}`);
          ElMessage.warning('用户信息获取失败，但登录状态已确认');
        }
      } else {
        wechatStore.log(`登录检查返回值: ${JSON.stringify(loginResult)}`);
        wechatStore.updateStatus({ running: true, loggedIn: false });
        wechatStore.log('微信未登录，请完成授权');
        ElMessage.warning('微信未登录，请确认已在微信上完成授权后再点击"确认登录完成"按钮');
      }
    } catch (loginError) {
      wechatStore.error(`登录状态检查失败: ${loginError.message}`);
      ElMessage.error(`登录检查失败: ${loginError.message}`);
      wechatStore.updateStatus({ running: true, loggedIn: false });
    }
  } catch (error) {
    wechatStore.error(`检查登录状态过程中出错: ${error.message}`);
    ElMessage.error(`操作失败: ${error.message}`);
    wechatStore.updateStatus({ running: true, loggedIn: false });
  } finally {
    isLoggedInLoading.value = false;
  }
}

// 启动微信服务
async function startService() {
  isStarting.value = true;
  try {
    wechatStore.log('正在启动微信服务...');
    const result = await window.electronAPI.startWechatService();
    wechatStore.log(`微信服务启动结果: ${result ? '成功' : '失败'}`);
    
    if (result) {
      ElMessage.success('微信服务已成功启动');
      // 更新 Pinia store
      wechatStore.updateStatus({ running: true, loggedIn: false });
    } else {
      ElMessage.error('微信服务启动失败');
      wechatStore.error('微信服务启动失败');
    }
  } catch (error) {
    wechatStore.error(`启动服务失败: ${error.message}`);
    ElMessage.error(`启动服务失败: ${error.message}`);
  } finally {
    isStarting.value = false;
  }
}

// 停止微信服务
async function stopService() {
  isStopping.value = true;
  try {
    wechatStore.log('正在停止微信服务...');
    await window.electronAPI.stopWechatService();
    wechatStore.log('微信服务已停止');
    ElMessage.success('微信服务已停止');
    
    // 更新 Pinia store
    wechatStore.clearUserInfo();
    wechatStore.updateStatus({ running: false, loggedIn: false });
  } catch (error) {
    wechatStore.error(`停止服务失败: ${error.message}`);
    ElMessage.error(`停止服务失败: ${error.message}`);
  } finally {
    isStopping.value = false;
  }
}
</script>

<style scoped>
.home-container {
  max-width: 1000px;
  margin: 0 auto;
}

.welcome-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-content {
  text-align: center;
  padding: 20px 0;
}

.action-buttons {
  margin-top: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  margin: 10px 0;
}

.quick-start-card {
  margin-bottom: 20px;
}

.quick-start-steps {
  padding-left: 20px;
}

.quick-start-steps li {
  margin-bottom: 15px;
}

.status-running {
  color: #67c23a;
  font-weight: bold;
}

.status-stopped {
  color: #f56c6c;
  font-weight: bold;
}
</style> 